package com.zhang.client.controller;

import com.zhang.client.bean.AccessTokenBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Package: com.zhang.client.controller
 * @ClassName: UserController
 * @Author: Think
 * @CreateTime: 2021/8/12 11:23
 * @Description:
 */
@Slf4j
@Controller
public class UserController {

    private static final String GET_ACCESS_TOKEN_URL = "http://localhost:8081/oauth/token?client_id={clientId}&client_secret={client_secret}&grant_type={grant_type}&redirect_uri={redirect_uri}&code={code}";
    private static final String GET_USER_NAME_URL = "http://localhost:8082/info/getUserName";

    @Autowired
    private RestTemplate restTemplate;
    private Map<String, String> paramMap = new HashMap<String, String>();

    /**
     * 登录首页，供用户选择使用授权服务进行登录
     *
     * @return
     */
    @GetMapping("/login")
    public String getUserName() {
        return "index";
    }

    /**
     * 供授权服务器重定向传回授权码
     * http://localhost:8080/getAuthorizationCode?code=UJfbrU
     *
     * @param authorizationCode
     * @return
     */
    @GetMapping("/getAuthorizationCode")
    public String getAuthorizationCode(@RequestParam("code") String authorizationCode, Model model) {
        log.info("授权码是{}", authorizationCode);

        // 组装参数
        paramMap.put("clientId", "iSchool");
        paramMap.put("client_secret", "mysecret");
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("redirect_uri", "http://localhost:8080/getAuthorizationCode");
        paramMap.put("code", authorizationCode);

        // 使用授权码再次访问授权服务器获取访问token
        AccessTokenBean accessTokenBean = restTemplate.getForObject(GET_ACCESS_TOKEN_URL, AccessTokenBean.class, paramMap);
        if (ObjectUtils.isEmpty(accessTokenBean) || ObjectUtils.isEmpty(accessTokenBean.getAccess_token())) {
            log.error("未成功获取访问令牌！");
            return null;
        }
        String accessToken = accessTokenBean.getAccess_token();
        log.info("访问令牌是{}", accessToken);

        // 使用访问令牌访问资源服务器获取用户信息
        HttpHeaders header = new HttpHeaders();
        // 指定JSON格式
        header.setContentType(MediaType.APPLICATION_JSON);
        header.add("Authorization", "Bearer " + accessToken);
        HttpEntity<String> httpEntity = new HttpEntity<>(null, header);
        ResponseEntity<String> responseEntity2 = restTemplate.exchange(GET_USER_NAME_URL, HttpMethod.GET, httpEntity, String.class);
        String userName = responseEntity2.getBody();
        // 设置用户信息并渲染页面
        model.addAttribute("userName", userName);
        return "hello";
    }

}
